/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.kuliza.app.webapp.controller;

import org.apache.commons.lang.StringUtils;
import com.kuliza.app.service.GenericManager;
import com.kuliza.app.model.Student;
import com.kuliza.app.webapp.controller.BaseFormController;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;


/**
 *
 * @author Gaurav Gupta
 */
public class StudentFormController extends BaseFormController {
    private GenericManager<Student, Long> studentManager = null;

    public void setStudentManager(GenericManager<Student, Long> studentManager) {
        this.studentManager = studentManager;
    }

    public StudentFormController() {
        setCommandClass(Student.class);
        setCommandName("student");
    }
    
    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");

        if (!StringUtils.isBlank(id)) {
            return studentManager.get(new Long(id));
        }
        
        return new Student();
    }
    
    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        log.debug("entering 'onSubmit' method...");

        Student student = (Student) command;
        boolean isNew = (student.getId() == null);
        String success = getSuccessView();
        Locale locale = request.getLocale();
        
        if (request.getParameter("delete") != null) {
            studentManager.remove(student.getId());
            saveMessage(request, getText("student.deleted", locale));
        } else {
            studentManager.save(student);
            String key = (isNew) ? "student.added" : "student.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                success = "redirect:studentform.html?id=" + student.getId();
            }
        }

        return new ModelAndView(success);
    }


    
}
